package com.lk.controller;

import com.lk.controller.base.BaseController;
import com.lk.domain.UserDao;
import com.lk.mapper.UserMapper;
import com.lk.util.Result;
import com.lk.util.ResultEnum;
import com.lk.util.ResultUtil;
import org.apache.commons.lang3.StringUtils;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;

@RestController
public class MyBootController extends BaseController {

    private static final Logger LOG = LogManager.getLogger(MyBootController.class);

    @Resource
    private StringRedisTemplate stringRedisTemplate;

    @Autowired
    private UserMapper userMapper;

    @GetMapping("/getUserInfo")
    public Result getUserInfo(long id) {

        if (id == 0) {
            return ResultUtil.failure();
        }
        UserDao user = userMapper.selectByPrimaryKey(id);
        return ResultUtil.successData(user);
    }

    @PostMapping("/addUser")
    public Result addUser(@RequestBody UserDao user) {

        if (user == null) {
            return ResultUtil.failure();
        }
        int insert = userMapper.insert(user);
        return insert == 1 ? ResultUtil.successData(user) : ResultUtil.failure();
    }

    @GetMapping("/redis/set")
    public Result redisSet(String name,String value){
        if (StringUtils.isBlank(name) || StringUtils.isBlank(value)){
            return ResultUtil.success(ResultEnum.PARAM_ERROR);
        }
        stringRedisTemplate.opsForValue().set(name,value);
        return ResultUtil.success();
    }

    @GetMapping("/redis/del")
    public Result redisDelete(String name){

        if (StringUtils.isBlank(name)){
            return ResultUtil.success(ResultEnum.PARAM_ERROR);
        }
        Boolean bool = stringRedisTemplate.delete(name);
        return bool ? ResultUtil.success():ResultUtil.failure();
    }

    @GetMapping("/redis/get")
    public Result redisGet(String name){
        if (StringUtils.isBlank(name)){
            return ResultUtil.success(ResultEnum.PARAM_ERROR);
        }
        return  ResultUtil.successData(stringRedisTemplate.opsForValue().get(name));
    }


}
